#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2017/12/2 0002 20:50
# @Author  : Arliki
# @Contact : hdknxycz@outlook.com 
# @Site    : 
# @File    : rob1.py
# @Software: PyCharm
import requests
import re
import os
import time
import subprocess
import redis


def get_new(url):
    _all = requests.get(url).content.decode('utf8')
    _new = re.findall('class="c54026" href="(.*?)"', _all, re.M | re.S)[0]
    return _new


def in_recode(cont, log):
    with open(log, 'w', encoding='utf8') as f:
        f.write(cont)


def out_recode(log):
    with open(log, 'r', encoding='utf8') as f:
        _old = f.read()
    return _old


def run():
    if os.path.exists('zpgg.log') and os.path.exists('xyxjh.log'):
        url = "http://zjc.haust.edu.cn/index/jycyzdzx/jysy/zpgg.htm"
        _new = get_new(url)
        _old = out_recode('zpgg.log')
        if _new == _old:
            url = "http://zjc.haust.edu.cn/index/jycyzdzx/jysy/xyxjh.htm"
            _new = get_new(url)
            _old = out_recode('xyxjh.log')
            if _new == _old:
                return 0
            else:
                in_recode(_new, 'xyxjh.log')
                return 1
        else:
            in_recode(_new, 'zpgg.log')
            return 1
    else:
        url = "http://zjc.haust.edu.cn/index/jycyzdzx/jysy/zpgg.htm"
        _new = get_new(url)
        in_recode(_new, 'zpgg.log')
        url = "http://zjc.haust.edu.cn/index/jycyzdzx/jysy/xyxjh.htm"
        _new = get_new(url)
        in_recode(_new, 'xyxjh.log')
        return 1


if __name__ == '__main__':
    r = redis.Redis(host='localhost', port=6379, db=1, password='5tgbnhy67ujm')
    while 1:
        need = run()
        if need:
            r.lpush('notify:hkdno', "http://zjc.haust.edu.cn/index/jycyzdzx/jysy/xyxjh.htm")
            r.lpush('notify:hkdno', "http://zjc.haust.edu.cn/index/jycyzdzx/jysy/zpgg.htm")
            ch1 = subprocess.Popen('./hkdnotify.sh > /dev/null 2>&1 &', shell=True)
            time.sleep(200)
            os.system('skill %s' % ch1.pid)
            ch1.kill()
        else:
            time.sleep(3600)
